package org.acghub.mtdb.core;

import java.util.concurrent.locks.Lock;

/**
 * @author zhouhe
 */
public class TTableStorage<K, V> extends AbstractTableStorage<K, V> {

    private boolean exists0(K key) {
        switch (engine().type()) {
            case JSON_MYSQL -> {
                return engine().exists(table().meta(), table().marshalJsonKey(key));
            }
            case DOCUMENT_MONGODB -> {
                return engine().exists(table().meta(), table().marshalDocumentKey(key));
            }
        }
        return false;
    }

    @Override
    public boolean exists(K key) {
        Lock lock = snapshotLock.readLock();
        lock.lock();
        try {
            TRecord<K, V> r = snapshot.get(key);
            if (r != null) {
                return r.exist();
            }
        } finally {
            lock.unlock();
        }
        return exists0(key);
    }

    @Override
    public V find(K key) {
        return null;
    }

    @Override
    public boolean verify(K key) {
        return true;
    }

    @Override
    public void truncate() {

    }

    @Override
    public long count() {
        return 0;
    }

    @Override
    public K minKey() {
        return null;
    }

    @Override
    public K maxKey() {
        return null;
    }

    @Override
    public K nextKey() {
        return null;
    }

    @Override
    public long marshalN() {
        return 0;
    }

    @Override
    public long marshal0() {
        return 0;
    }

    @Override
    public long snapshot() {
        return 0;
    }

    @Override
    public long flush0() {
        return 0;
    }

    @Override
    public void cleanup() {

    }

    @Override
    public void onChanged(TRecord<K, V> r) {
        if (r.state() == TRecord.State.REMOVE) {
            changed.remove(r.getKey());
            marshal.remove(r.getKey());
        } else {
            changed.put(r.getKey(), r);
        }
    }
}
